"""
@Project:ruiji
@File:index.py
@Author:马可
@Date:上午 09:38
"""
from flask import Blueprint,jsonify,request
from db import db
from utils.myredis import r
import json

index_blue = Blueprint('index',__name__)


# 获取商家信息
@index_blue.route("/getshops")
def getshops():
    code = '001'
    key = "shop"+code
    # r.removeall_str(key)   # 删除redis信息
    shop = r.get_str(key)
    if not shop:
        # 并发访问时允许一人访问
        res = r.setnx_str(key+'exit',key+'exit')
        # print('aaa')
        if res:
            # print('bbb')
            sql = "select * from shops where code='001'"
            shop = db.find(sql)
            r.set_str(key,json.dumps(shop))
    else:
        shop = json.loads(shop)
    return jsonify({
        'code':200,
        'shops':shop,
    })


# 获取所有分类
@index_blue.route('/getcates')
def getcates():
    cates = r.get_str('cates')
    if not cates:
        sql = "select id,name from category order by sort asc"
        res = db.find_all(sql)
        r.set_str('cates',json.dumps(res))
    else:
        res = json.loads(cates)
    data = []
    if res:
        data = [{
            'id':str(i['id']),
            'text':i['name'],
        } for i in res]
    return jsonify({
        'code':200,
        'catelist':data,
    })



#根据分类id获取此分类下的所有商品
@index_blue.route("/getGoodsBycateid")
def getGoodsBycateid():
    #获取分类id
    cateid = request.form.get('id')
    #获取缓存中此分类下的商品
    print('aaa',cateid)
    goods = r.get_str('goods')
    #如果不存在查询
    if not goods:
        sql="select id,name,price,image,description from dish where category_id=%d and is_deleted=0"%(int(cateid))
        res = db.find_all(sql)
        #把decimal转成float
        data = [{'id':i['id'],'name':i['name'],'price':float(i['price']),'image':i['image'],'description':i['description']} for i in res]
        #加入缓存
        r.set_str('goods',json.dumps(data))
    else:
        data = json.loads(goods)
    return jsonify({"code":200,'goodslist':data})









